package com.simple.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.simple.service.EsMarkService;
import com.simple.service.QuestionSearchService;
import com.simple.service.QuestionSearchServiceImp;
import com.simple.service.YoudaoMarkService;
import com.simple.util.HttpUtil;
import com.simple.util.OCRYouDaoUtil;
import com.simple.vo.GeneralName;
import com.simple.vo.JsonResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 题目搜索服务
 * @author lub
 */

@CrossOrigin
@Controller
@RequestMapping("/resource/questionSearch")
public class QuestionSearchController {
	
	@Autowired
	private QuestionSearchService questionSearchService;
	@Autowired
	QuestionSearchServiceImp questionSearchServiceImp;

	
	@RequestMapping("/test")
	public ModelAndView test() {
		ModelAndView modelAndView = new ModelAndView("/question");
		return modelAndView;
	}
	
	
	@RequestMapping("/testmark")
	public ModelAndView testmark() {
		ModelAndView modelAndView = new ModelAndView("/question_mark");
		return modelAndView;
	}


    @RequestMapping("/unlockMarking")
    @ResponseBody
    public JsonResultData unlockMarking() {
        JsonResultData result = JsonResultData.success();
        int rs = questionSearchService.unlockMarking();
        result.addObject("count",rs);
        return result;
    }


	@RequestMapping("/initLoc")
	@ResponseBody
	public JsonResultData initLoc() {
		JsonResultData result = JsonResultData.success();
		questionSearchService.initData();
		return result;
	}


	@RequestMapping("/init")
	@ResponseBody
	public JsonResultData init(@RequestBody String requestBody) {
		JsonResultData result = JsonResultData.success();
		JSONObject json = JSONObject.parseObject(requestBody);
		String names = json.getString("names");
		System.out.println("names:" + names);
		if(StringUtils.isEmpty(names)){
			return result;
		}
		String [] nameArr = names.split(",");
		questionSearchService.initData( Arrays.asList(nameArr));
		return result;
	}


	@RequestMapping("/export")
	@ResponseBody
	public void downloadDataExecl(HttpServletResponse response) throws Exception {
		questionSearchService.exportExecl(response);
	}


	@RequestMapping("/zip")
	@ResponseBody
	public void downloadDataExecl(HttpServletResponse response,String type) throws IOException {
		questionSearchService.zip(response,type);
	}

    @RequestMapping("/turn")
    @ResponseBody
    public String turn(HttpServletResponse response,String id) throws IOException {
        System.out.println("turn id=" + id);
        return HttpUtil.get("http://onlinelibres.noahedu.com/NRMP_TEST/question/view/simple_view/" + id,10000);
    }


	@RequestMapping("/getOneImg")
	@ResponseBody
	public JsonResultData getOneImg(HttpServletRequest request) {
		JsonResultData result = JsonResultData.success();
		Map img = questionSearchService.getOneImg();
		result.addObject("img", img);
		result.addObject("deal", questionSearchService.getDeal());
		if(StringUtils.isEmpty(img)) {
			result.turnError("已经是最后一张了");
		}
		return result;
	}


	@RequestMapping("/getPrdRs")
	@ResponseBody
	public String getPrdRs(HttpServletRequest request,String fileName) throws Exception {
		return questionSearchService.searchQuestionByImageHttp(fileName);
	}





	@RequestMapping("/updateMark")
	@ResponseBody
	public JsonResultData updateMark(HttpServletRequest request,@RequestBody JSONObject json ) {
		JsonResultData result = JsonResultData.success();
		try {
			//JSONObject json = JSONObject.parseObject(requestBody);
			String img_name = json.getString("img_name");
			String is_valid = json.getString("is_valid");
			if ("0".equals(is_valid)) {
				questionSearchService.invalid(img_name);
				return result;
			}else{
				is_valid = "1";
			}
			String is_point = json.getString("is_point");
			int search_pos = -1;
			if (!StringUtils.isEmpty(json.getString("search_pos"))) {
				search_pos = Integer.parseInt(json.getString("search_pos"));
			}
			String question_id =json.getString("question_id");
			Map map = new HashMap();
			map.put("img_name", img_name);
			map.put("is_point", is_point);
			map.put("is_valid", is_valid);
			if (search_pos != -1) {
				map.put("search_pos", search_pos);
				map.put("question_id", Integer.parseInt(question_id));
				map.put("is_success","1");
			}else{
				map.put("is_success","0");
			}
			map.put("is_marking", "0");
			map.put("is_mark", "1");
			questionSearchService.updateMark(map);
		}catch (Exception e){
			e.printStackTrace();
			result.turnError("提交失败");
		}

		return result;
	}

	@RequestMapping("/searchQuestionByImageUp")
	@ResponseBody
	public JsonResultData searchQuestionByImageUp(HttpServletRequest request, MultipartFile file) {
		JsonResultData result = JsonResultData.success();
		String oldName = file.getOriginalFilename();
		String uniqueName = GeneralName.getUniqueName();
		File cacheFile = new File(request.getServletContext().getRealPath("/") + uniqueName
				+ oldName.substring(oldName.lastIndexOf("."), oldName.length()));
		try {
			file.transferTo(cacheFile);
			List<JSONObject> questionList = questionSearchServiceImp.searchQuestionByImage(null,cacheFile);
			result.addObject("questionList", questionList);
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("搜索失败");
		}
		finally {
			cacheFile.deleteOnExit();
		}
		return result;
	}

	@RequestMapping("/searchQuestionByImagePointUp")
	@ResponseBody
	public JsonResultData searchQuestionByImagePointUp(HttpServletRequest request, MultipartFile file) {
		JsonResultData result = JsonResultData.success();
		String oldName = file.getOriginalFilename();
		String uniqueName = GeneralName.getUniqueName();
		File cacheFile = new File(request.getServletContext().getRealPath("/") + uniqueName
				+ oldName.substring(oldName.lastIndexOf("."), oldName.length()));
		try {
			file.transferTo(cacheFile);
			List<JSONObject> questionList = questionSearchService.searchQuestionByImageForPointTest(null,cacheFile);
			result.addObject("questionList", questionList);
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("搜索失败");
		}
		finally {
			cacheFile.deleteOnExit();
		}
		return result;
	}
	
	
	
	@RequestMapping("/searchQuestionByImageForTest")
	@ResponseBody
	public JsonResultData searchQuestionByImageForTest(HttpServletRequest request, @RequestBody String requestBody) {
		JsonResultData result = JsonResultData.success();
		JSONObject json = JSONObject.parseObject(requestBody);
		String name = json.getString("img_name");
		try {
			List<JSONObject> questionList = questionSearchServiceImp.searchQuestionByImage(name,null);
			result.addObject("questionList", questionList);
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("搜索失败");
		}
		finally {
		}
		return result;
	}


    @RequestMapping("/getNrmpText")
    @ResponseBody
    public JsonResultData getNrmpText(HttpServletRequest request,@RequestBody String requestBody) {
        String resultText = "{}";
        JsonResultData result = JsonResultData.success();
        try {
            JSONObject json = JSONObject.parseObject(requestBody);
            String name = json.getString("img_name");
            resultText = questionSearchService.getNrmpText(name);
            System.out.println(resultText);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        result.addObject("result", resultText);
        return result;
    }
	
	
	@RequestMapping("/searchQuestionByImageForPointTest")
	@ResponseBody
	public JsonResultData searchQuestionByImageForPointTest(HttpServletRequest request, @RequestBody String requestBody /*MultipartFile file*/) {
		JsonResultData result = JsonResultData.success();
		JSONObject json = JSONObject.parseObject(requestBody);
		String name = json.getString("img_name");
		try {
			List<JSONObject> questionList = questionSearchService.searchQuestionByImageForPointTest(name,null);
			result.addObject("questionList", questionList);
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("搜索失败");
		}
		finally {
		}
		return result;
	}

	/*
	@RequestMapping("/searchQuestionByTextForTest")
	@ResponseBody
	public JsonResultData searchQuestionByText(HttpServletRequest request, String text) {
		JsonResultData result = JsonResultData.success();
		try {
			List<JSONObject> questionList = questionSearchService.searchQuestionByTextForTest(text);
			result.addObject("questionList", questionList);
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("搜索失败");
		}
		return result;
	}
	
	@RequestMapping("/getSimilarQuestions")
	@ResponseBody
	public JsonResultData getSimilarQuestions(long questionId) {
		JsonResultData result = JsonResultData.success();
		try {
			List<JSONObject> jsonObject = questionSearchService.getSimilarQuestions(questionId);
			result.addObject("questions", jsonObject);
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("搜索失败:"+e.getMessage());
		}
		return result;
	}
	*/



	@RequestMapping("/ocrQuestionByImageUp")
	@ResponseBody
	public JsonResultData ocrQuestionByImageUp(HttpServletRequest request, MultipartFile file) {
		JsonResultData result = JsonResultData.success();
		String oldName = file.getOriginalFilename();
		String uniqueName = GeneralName.getUniqueName();
		File cacheFile = new File(request.getServletContext().getRealPath("/") + uniqueName
				+ oldName.substring(oldName.lastIndexOf("."), oldName.length()));
		try {
			file.transferTo(cacheFile);
			String ocrRs  = questionSearchService.ocrQuestionByImageUp(cacheFile);
			result.addObject("ocrRs", ocrRs);
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("搜索失败");
		}
		finally {
			cacheFile.deleteOnExit();
		}
		return result;
	}


	@RequestMapping("/esQuestionByText")
	@ResponseBody
	public JsonResultData esQuestionByText(HttpServletRequest request, @RequestBody JSONObject json ) {
		JsonResultData result = JsonResultData.success();
		try {
			JSONArray esRs = questionSearchService.esQuestionByText(json.getString("ocr"));
			result.addObject("esRs", esRs);
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("搜索失败");
		}
		finally {
		}
		return result;
	}




	@Autowired
	EsMarkService esMarkService;

	@RequestMapping("/esInit")
	@ResponseBody
	public JsonResultData esInit(HttpServletRequest request) {
		JsonResultData result = JsonResultData.success();
		try {
			esMarkService.initDataSql();
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("失败");
		}
		finally {
		}
		return result;
	}






	@RequestMapping("/initDeal")
	@ResponseBody
	public JsonResultData initDeal(@RequestBody String requestBody) {
		JsonResultData result = JsonResultData.success();
		JSONObject json = JSONObject.parseObject(requestBody);
		String imgs = json.getString("imgs");
		String [] imgArr = imgs.split(",");
		esMarkService.updateDeal(CollectionUtils.arrayToList(imgArr));
		return result;
	}



	@RequestMapping("/getOneImgEs")
	@ResponseBody
	public JsonResultData getOneImgEs(HttpServletRequest request) {
		JsonResultData result = JsonResultData.success();
		Map img = esMarkService.getOneImg();
		result.addObject("img", img);
		result.addObject("deal", esMarkService.getDealEs());
		if(StringUtils.isEmpty(img)) {
			result.turnError("已经是最后一张了");
		}
		return result;
	}




	@RequestMapping("/ocrQuestionByName")
	@ResponseBody
	public JsonResultData ocrQuestionByImageUp(HttpServletRequest request, String name) {
		JsonResultData result = JsonResultData.success();
		try {
			String ocrRs  = questionSearchService.ocrQuestionByImageUp(name);
			result.addObject("ocrRs", ocrRs);
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("搜索失败");
		}
		finally {
		}
		return result;
	}

	@RequestMapping("/updateMarkEs")
	@ResponseBody
	public JsonResultData updateMarkEs(HttpServletRequest request,@RequestBody JSONObject json ) {
		JsonResultData result = JsonResultData.success();
		try {
			//JSONObject json = JSONObject.parseObject(requestBody);
			String img_name = json.getString("img_name");
			String is_es = json.getString("is_es");

			Map map = new HashMap();
			map.put("img_name", img_name);
			map.put("is_es", is_es);
			map.put("is_marking", "0");
			map.put("is_mark", "1");
			esMarkService.updateMark(map);
		}catch (Exception e){
			e.printStackTrace();
			result.turnError("提交失败");
		}

		return result;
	}


	@Autowired
	YoudaoMarkService youdaoMarkService;

	@RequestMapping("/getOneImgYoudao")
	@ResponseBody
	public JsonResultData getOneImgYoudao(HttpServletRequest request) {
		JsonResultData result = JsonResultData.success();
		Map img = youdaoMarkService.getOneImg();
		result.addObject("img", img);
		result.addObject("deal", youdaoMarkService.getDealYoudao());
		if(StringUtils.isEmpty(img)) {
			result.turnError("已经是最后一张了");
		}
		return result;
	}




	@RequestMapping("/youdaoQuestionByName")
	@ResponseBody
	public JsonResultData youdaoQuestionByImageUp(HttpServletRequest request, String name) {
		JsonResultData result = JsonResultData.success();
		try {
			JSONObject ocrRs  = youdaoMarkService.youdaoQuestionByImageUp(name);
			if(null == ocrRs){
				result.turnError("搜索失败");
				return result;
			}
			result.addObject("ocrRs", ocrRs);
		}
		catch(Exception e) {
			e.printStackTrace();
			result.turnError("搜索失败");
		}
		finally {
		}
		return result;
	}

	@RequestMapping("/updateMarkYoudao")
	@ResponseBody
	public JsonResultData updateMarkYoudao(HttpServletRequest request,@RequestBody JSONObject json ) {
		JsonResultData result = JsonResultData.success();
		try {
			//JSONObject json = JSONObject.parseObject(requestBody);
			String img_name = json.getString("img_name");
			String is_es = json.getString("is_es");

			Map map = new HashMap();
			map.put("img_name", img_name);
			map.put("is_es", is_es);
			map.put("is_marking", "0");
			map.put("is_mark", "1");
			youdaoMarkService.updateMark(map);
		}catch (Exception e){
			e.printStackTrace();
			result.turnError("提交失败");
		}

		return result;
	}




}
